package com.hxh.rpc.consumer;

import com.hxh.rpc.model.RpcResponse;
import com.hxh.rpc.registry.ServiceRegistry;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cglib.proxy.Proxy;

/**
 * 生成rpc consumer代理bean的工厂
 *
 * @author hxh
 * @date 2022/3/2
 * @since 1.0
 */
@Slf4j
@Data
public class RpcConsumerFactoryBean implements FactoryBean<Object> {
    /**
     * 服务接口类
     */
    private Class<?> interfaceClass;
    /**
     * 实际对象
     */
    private Object object;

    private String serviceVersion;

    private ServiceRegistry serviceRegistry;

    /**
     * 初始化方法，通过动态代理生成bean
     */
    public void init() {
        this.object = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new RpcInvokeHandler<RpcResponse>(serviceVersion, serviceRegistry));
        log.info("RpcConsumerFactoryBean getObject: {}", interfaceClass.getName());
    }

    @Override
    public Object getObject() {
        return this.object;
    }

    @Override
    public Class<?> getObjectType() {
        return this.interfaceClass;
    }

}
